#!/bin/bash

# 检测是否以root身份运行
if [ "$(id -u)" -eq 0 ]; then
    echo -e "\033[31m警告：你正在以root身份运行此脚本，脚本在需要的适合会自动向你请求，全局root运行可能造成路径和权限混乱。\033[0m（\033[31m不推荐\033[0m）\033[0m你确定要继续吗？ (yes/no)\033[0m"
    read answer
    if [ "$answer" != "yes" ]; then
        echo -e "\033[31m安装已取消。安装进度：0%\033[0m"
        exit 1
    fi
fi

detect_package_manager() {
    if command -v apt &> /dev/null; then
        echo "apt"
        elif command -v yum &> /dev/null; then
        echo "yum"
    else
        echo "none"
    fi
}

# Function to format speed for display
format_speed() {
    local speed_bps=$1
    if (( speed_bps > 1048576 )); then
        # MB/s
        local speed_mbs=$((speed_bps / 1048576))
        echo "${speed_mbs} MB/s"
    elif (( speed_bps > 1024 )); then
        # KB/s
        local speed_kbs=$((speed_bps / 1024))
        echo "${speed_kbs} KB/s"
    else
        # B/s
        echo "${speed_bps} B/s"
    fi
}

# 测速
speed_test_and_clone() {
    local -a mirrors=(
        "https://ghfast.top"
        "https://git.yylx.win"
        "https://gh-proxy.com"
        "https://ghfile.geekertao.top"
        "https://j.1win.ggff.net"
        "https://jiashu.1win.eu.org"
    )
    # 测速目标
    local check_url="https://raw.githubusercontent.com/NapNeko/NapCatQQ/main/package.json"
    local target_repo="https://github.com/avilliai/Eridanus.git"
    local timeout=10
    local clone_successful=false

    for i in {1..3}; do
        echo -e "\033[32m第 $i/3 次尝试克隆...\033[0m"
        local best_mirror=""
        local best_speed=0

        # 测速直连
        echo -e "\033[36m测速中: 直连 GitHub...\033[0m"
        local curl_output
        curl_output=$(curl -L --connect-timeout ${timeout} -o /dev/null -s -w "%{http_code}:%{speed_download}" "${check_url}")
        local status=$(echo "${curl_output}" | cut -d: -f1)
        local download_speed=$(echo "${curl_output}" | cut -d: -f2 | cut -d. -f1)

        if [ "${status}" -eq 200 ] && [ "${download_speed}" -gt 0 ]; then
            local formatted_speed=$(format_speed "${download_speed}")
            echo -e "\033[32m测速结果: 直连 - ${formatted_speed}\033[0m"
            best_speed=${download_speed}
            best_mirror="direct"
        else
            echo -e "\033[31m测速失败: 直连\033[0m"
        fi

        # 测速镜像
        if [ ${#mirrors[@]} -gt 0 ]; then
            for mirror in "${mirrors[@]}"; do
                echo -e "\033[36m测速中: ${mirror}...\033[0m"
                local test_target_url="${mirror}/${check_url}"
                curl_output=$(curl -L --connect-timeout ${timeout} -o /dev/null -s -w "%{http_code}:%{speed_download}" "${test_target_url}")
                status=$(echo "${curl_output}" | cut -d: -f1)
                download_speed=$(echo "${curl_output}" | cut -d: -f2 | cut -d. -f1)

                if [ "${status}" -eq 200 ] && [ "${download_speed}" -gt "${best_speed}" ]; then
                    local formatted_speed=$(format_speed "${download_speed}")
                    echo -e "\033[32m测速结果: ${mirror} - ${formatted_speed}\033[0m"
                    best_speed=${download_speed}
                    best_mirror=${mirror}
                elif [ "${status}" -ne 200 ]; then
                     echo -e "\033[31m测速失败: ${mirror} (HTTP: ${status})\033[0m"
                fi
            done
        fi

        if [ -z "${best_mirror}" ]; then
            echo -e "\033[31m所有源测速失败，无法进行克隆。请检查网络连接。\033[0m"
            break
        fi

        local clone_url=""
        if [ "${best_mirror}" == "direct" ]; then
            echo -e "\033[32m选择最快线路: 直连 GitHub\033[0m"
            clone_url="${target_repo}"
        else
            echo -e "\033[32m选择最快线路: ${best_mirror}\033[0m"
            clone_url="${best_mirror}/${target_repo}"
        fi

        echo -e "\033[32m正在使用 ${clone_url} 克隆仓库...\033[0m"
        git clone --depth 1 "${clone_url}" Eridanus
        if [ $? -eq 0 ]; then
            clone_successful=true
            break
        else
            echo -e "\033[31m使用 ${best_mirror} 克隆失败。\033[0m"
            # 从测速集中删除失败源
            if [ "${best_mirror}" != "direct" ]; then
                local temp_mirrors=()
                for m in "${mirrors[@]}"; do
                    if [ "$m" != "${best_mirror}" ]; then
                        temp_mirrors+=("$m")
                    fi
                done
                mirrors=("${temp_mirrors[@]}")
            fi
        fi
    done

    if [ "${clone_successful}" = true ]; then
        return 0
    else
        return 1
    fi
}

# 红色中文提示
echo -e "\033[32m--------------\033[0m\033[1;41;32m 严禁商用声明 \033[0m\033[32m---------------------\033[0m\n"
echo -e "\033[1;31mLinux 部署项目遵守\033[0m \033[1;4;36mCreative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)\033[0m \033[1;31m协议。"
echo -e "未经许可，严禁将该项目用于任何商业用途。任何人将该项目商用所获取的任何非法利益与本项目无关。\033[0m"
echo -e "\033[3;4;31m如果你是付费后获取的本脚本，那恭喜你\033[0m\033[3;4;32m被骗了\033[0m\033[3;4;31m。\033[0m\n"
echo -e "\033[32m--------------\033[0m\033[1;41;32m 严禁商用声明 \033[0m\033[32m---------------------\033[0m\n\n"



echo -e "\033[31m本脚本仅适配了带有apt和yum的系统，其他系统请根据官方教程手动安装或者根据本脚本的逻辑自行安装\033[0m"
echo -e "\033[31m安装过程中如果提示需要输入yes或y 或者选择1 2 3，请输入合适的选项。\033[0m"
echo -e "\033[33m安装过程可能会持续20-60分钟，这取决于你的网速和处理器性能\033[0m"
echo -e "\033[33mlinux上部署肯定没有windows那么方便，但既然你选择了linux，那相信你有勇气和能力解决各种问题\033[0m"


# 等待用户确认
read -p "按回车键继续..."

# 定义颜色
RED='\033[0;31m'
NC='\033[0m' # No Color

# 提示用户选择下载地址
echo -e "\n\033[32m选择Eridanus下载地址\033[0m\n"
echo "请选择下载地址："
echo -e "\033[33m1. 自动测速选择最快镜像 (推荐)\033[0m"
echo -e "\033[33m2. 直接使用GitHub地址 (如果网络良好)\033[0m"

read -t 10 -p "请输入选项 (1/2，10秒后默认为1): " choice
if [ $? -ne 0 ]; then
    echo -e "\n${RED}倒计时结束，使用默认选项 1。${NC}"
    choice="1"
fi

ARCH=$(uname -m)
# 检查系统架构
if [ "$ARCH" != "x86_64" ]; then
    echo -e "\e[3;31m警告: 经过测试 \e[33mMiniconda\e[31m 在非\e[33m x86_64 \e[31m架构的 CPU 上安装会出现问题，可能会出现异常情况。\n推荐改用\e[33m x86_64 \e[31m或者\e[33m Windows 平台\e[31m\e[0m"
    read -t 30 -p "是否继续安装? (y/N, 30秒后自动继续): " answer
    if [ $? -gt 128 ]; then
        echo -e "\n等待超时，继续安装..."
    else
        case $answer in
            [nN])
                echo "用户取消安装"
                exit 1
                ;;
        esac
    fi
fi


package_manager=$(detect_package_manager)



echo -e "\033[32m安装进度：5%\033[0m"

isCondaInstalled=false
# 检查是否已经安装了conda
if command -v conda &> /dev/null; then
    echo -e "\033[32mConda已经安装。\033[0m"
    echo -e "\033[32m安装进度：10%\033[0m"
    isCondaInstalled=true
else
    # 获取CPU架构
    ARCH=$(uname -m)

    # 根据CPU架构设置Miniconda安装脚本的URL
    if [ "$ARCH" == "x86_64" ]; then
        MINICONDA_URL="https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh"
    elif [ "$ARCH" == "aarch64" ]; then
        MINICONDA_URL="https://github.moeyy.xyz/https://github.com/conda-forge/miniforge/releases/download/4.12.0-0/Mambaforge-4.12.0-0-Linux-aarch64.sh"
    elif [ "$ARCH" == "ppc64le" ]; then
        MINICONDA_URL="https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-ppc64le.sh"
    elif [ "$ARCH" == "s390x" ]; then
        MINICONDA_URL="https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-s390x.sh"
    else
        echo -e "\033[31m不支持的架构: $ARCH\033[0m"
        echo -e "\033[31m安装进度：10%\033[0m"
        exit 1
    fi

    # 下载Miniconda安装脚本
    echo -e "\033[31m正在下载适用于 $ARCH 架构的Miniconda安装脚本...\033[0m"
    wget $MINICONDA_URL -O Miniconda3-latest-Linux-$ARCH.sh

    # 检查下载是否成功
    if [ $? -ne 0 ]; then
        echo -e "\033[31m下载Miniconda安装脚本失败。\033[0m"
        exit 1
    fi

    # 设置脚本的权限为+x
    echo -e "\033[32m正在设置Miniconda安装脚本的权限...\033[0m"
    chmod +x Miniconda3-latest-Linux-$ARCH.sh

    # 执行安装脚本
    echo -e "\033[32m正在执行Miniconda安装脚本...\033[0m"
    ./Miniconda3-latest-Linux-$ARCH.sh -b -p $HOME/miniconda3
    export PATH="$HOME/miniconda3/bin:$PATH"
    eval "$($HOME/miniconda3/bin/conda shell.bash hook)"
    conda init

    # 检查安装是否成功
    if [ $? -eq 0 ]; then
        echo -e "\033[32mMiniconda安装成功。\033[0m"
        echo -e "\033[32m安装进度：10%\033[0m"
    else
        echo -e "\033[31mMiniconda安装失败。\033[0m"
        exit 1
    fi
fi

# 修改conda的软件源配置文件
echo -e "\033[32m正在配置conda的软件源...\033[0m"
cat > ~/.condarc <<EOL
channels:
  - defaults
show_channel_urls: true
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch-lts: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  deepmodeling: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/
EOL

echo -e "\033[32mconda软件源配置完成。\033[0m"

# 清除conda缓存
echo -e "\033[32m正在清除conda缓存...\033[0m"
conda clean -i -y

# 创建Python 3.11虚拟环境
echo -e "\033[32m正在创建Python 3.11虚拟环境...\033[0m"
conda create -y -n qqbot python=3.11

if [ $? -eq 0 ]; then
    echo -e "\033[32m虚拟环境创建成功。正在进入虚拟环境...\033[0m"
    # 激活虚拟环境
    if [ "$isCondaInstalled" = true ]; then
        conda_path=$(which conda)
        if [ -z "$conda_path" ]; then
            echo -e "\033[31m无法找到conda的路径。\033[0m"
            exit 1
        fi
        # 获取conda的绝对路径
        conda_dir=$(dirname "$conda_path")
        # 激活虚拟环境
        source "$conda_dir/../bin/activate" qqbot
        python -V
    else
        source "$HOME/miniconda3/bin/activate" qqbot
        python -V
    fi
    echo -e "\033[32m已进入虚拟环境qqbot。\033[0m"
else
    echo -e "\033[31m虚拟环境创建失败。\033[0m"
    exit 1
fi

echo -e "\033[32m安装进度：15%\033[0m"

# 克隆GitHub仓库
echo -e "\033[32m正在克隆GitHub仓库...\033[0m"

clone_success=false
if [ "$choice" == "2" ]; then
    echo -e "\033[32m选择直连GitHub，开始克隆...\033[0m"
    git clone --depth 1 "https://github.com/avilliai/Eridanus.git" Eridanus
    if [ $? -eq 0 ]; then
        clone_success=true
    fi
else
    echo -e "\033[32m选择自动测速，开始测试...\033[0m"
    if speed_test_and_clone; then
        clone_success=true
    fi
fi

if [ "$clone_success" = true ]; then
    echo -e "\033[32m克隆Eridanus仓库成功。\033[0m"
else
    echo -e "\033[31mGit 克隆失败，尝试使用 wget 直接下载源码...\033[0m"
    wget https://ghproxy.net/https://github.com/avilliai/Eridanus/archive/refs/heads/master.zip -O Eridanus.zip
    if [ $? -eq 0 ]; then
        unzip Eridanus.zip -d .
        mv Eridanus-main Eridanus
        rm Eridanus.zip
        echo -e "\033[32m使用wget下载并解压仓库成功。\033[0m"
    else
        echo -e "\033[31m所有下载方式均失败。请检查网络或手动下载 Eridanus 源码。\033[0m"
        exit 1
    fi
fi

# 尝试解析符号链接获取实际路径
if command -v readlink &> /dev/null; then
    script_path=$(readlink -f "$0")
elif command -v realpath &> /dev/null; then
    script_path=$(realpath "$0")
else
    # 不支持 readlink 或 realpath 的情况
    script_path=$(cd "$(dirname "$0")"; pwd -P)/$(basename "$0")
fi
# 获取当前脚本所在的目录（绝对路径）
script_dir=$(dirname "$script_path")

# 获取父目录（绝对路径）
parent_dir=$(cd "$script_dir/.."; pwd)
echo -e "\033[32m安装进度：35%\033[0m"
# 修改文件权限和内容
chmod +x -R Eridanus
#sed -i 's/python.exe/python/g' Eridanus/main.py


# 升级pip并修改pip源为清华源
echo -e "\033[32m正在升级pip并修改pip源为清华源...\033[0m"
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

# 安装依赖
echo -e "\033[32m正在安装依赖...\033[0m"
# 获取当前Python版本信息
version=$(python3 --version 2>&1)
python_check="false"
# 使用正则表达式匹配Python 3.9.*
if [[ $version =~ Python\ 3\.11\.* ]]; then
    echo "当前的Python版本是3.11.*"
    python_check="true"
else
    echo "当前的Python版本不是3.11.*，而是 $version"
    python_check="false"
fi

python_version=""
if [ "$ARCH" == "aarch64" ]; then

    if [ "$package_manager" = "apt" ];then
        sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt install -qq -y build-essential make gcc g++ zlib1g-dev libncurses5-dev libncursesw5-dev libreadline-dev libssl-dev libbz2-dev libsqlite3-dev wget curl llvm libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev libasound2-dev libsndfile1-dev cmake libgdbm-dev libnss3-dev ccache dos2unix libzbar0
        sudo apt --fix-broken install -y
    else
        sudo yum install -q -y build-essential make gcc g++ zlib1g-dev libncurses5-dev libncursesw5-dev libreadline-dev libssl-dev libbz2-dev libsqlite3-dev wget curl llvm libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev libasound2-dev libsndfile1-dev cmake libgdbm-dev libnss3-dev ccache nss dbus-libs at-spi2-atk gtk3 cups-libs zip unzip jq curl libzbar0
    fi

    python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
    pip  install  -r Eridanus/requirements.txt
    pip  install  -r Eridanus/requirements.txt
    #pip install aiohttp==3.10.5 bilibili-api-python==16.3.0
    python_version="python"
else
    python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip
    pip  install  -r Eridanus/requirements.txt
    #pip install aiohttp==3.10.5 bilibili-api-python==16.3.0
    python_version="python"
fi

if [ $? -eq 0 ]; then
    echo -e "\033[32m依赖安装成功。\033[0m"
else
    echo -e "\033[31m依赖安装失败。\033[0m"
    exit 1
fi
echo -e "\033[32m安装进度：40%\033[0m"



# 删除指定文件和文件夹
echo -e "\033[33m正在删除临时产生且无用的文件和文件夹...\033[0m"

rm -f Miniconda3-latest-Linux-x86_64.sh

echo -e "\033[32m安装进度：85%\033[0m"

CURRENT_DIR=$script_dir
echo -e "\033[33m脚本当前文件夹路径: $CURRENT_DIR\033[0m"

# 创建start文件夹
START_DIR="$CURRENT_DIR/start"
mkdir -p $START_DIR/direct
echo -e "\033[32m创建start文件夹: $START_DIR\033[0m\n"

# 创建2_Eridanus.sh脚本
cat > $START_DIR/direct/2_Eridanus.sh <<EOL
#!/bin/bash
source $HOME/miniconda3/bin/activate qqbot
cd $CURRENT_DIR/Eridanus/
$python_version $CURRENT_DIR/Eridanus/main.py >> $START_DIR/eridanus_log.txt 2>&1
EOL
chmod +x $START_DIR/direct/2_Eridanus.sh
echo -e "\033[32m创建脚本: $START_DIR/direct/2_Eridanus.sh\033[0m\n"

# 创建2_Eridanus_withoutgui.sh脚本
cat > $START_DIR/2_Eridanus_withoutgui.sh <<EOL
#!/bin/bash
echo -e "\033[31m请勿试图切换到tmux窗口，否则可能导致进程关闭，如果要查询进程情况，请直接cat对应日志\033[0m"
tmux new-session -d -s Eridanus $START_DIR/direct/2_Eridanus.sh
EOL
chmod +x $START_DIR/2_Eridanus_withoutgui.sh
echo -e "\033[32m创建脚本: $START_DIR/2_Eridanus_withoutgui.sh\033[0m\n"

# 创建update.sh脚本
cat > $START_DIR/update.sh <<EOL
#!/bin/bash
clear
if [[ \$EUID -ne 0 ]]; then
   echo "此脚本需要 root 权限，正在尝试使用 sudo 获取..." >&2
   sudo chmod +x -R $CURRENT_DIR/Eridanus/
fi
cd $CURRENT_DIR/Eridanus/
source $HOME/miniconda3/bin/activate qqbot
cd $CURRENT_DIR/Eridanus/
$python_version $CURRENT_DIR/Eridanus/tool.py | tee $START_DIR/update_log.txt
EOL
chmod +x $START_DIR/update.sh
echo -e "\033[32m创建脚本: $START_DIR/update.sh\033[0m\n"

curl -o $START_DIR/gui.sh https://gitee.com/laixi_lingdun/eridanus_deploy/raw/master/gui.sh 


chmod  +x -R $CURRENT_DIR

echo -e "\033[33m安装进度：100%\033[0m"
echo -e "\n\n\n\033[32m所有组件已经安装完毕，请仔细阅读以下内容：\033[0m"
echo -e "\033[31m-------------------------------------------------------------------------------------------------\n\033[0m"
echo -e "\n\033[32m本脚本是为了方便学习Eridanus而编写，严禁将机器人和部署脚本用于违法违规用途，使用本脚本和机器人所造成的一切后果自行承担。\033[0m"
echo -e "\033[33m请执行 bash $START_DIR/gui.sh 来启动和管理机器人\033[0m"
echo -e "\033[33m待成功启动 Eridanus 后请查看日志然后找到Webui地址,进入Webui进行配置和管理\033[0m"
echo -e "\033[32m机器人其他详细配置请参见$CURRENT_DIR/Eridanus/config/中的配置文件所含注释（预计以后会出GUI界面）\033[0m\n"
echo -e "\033[31m-------------------------------------------------------------------------------------------------\n\033[0m"
# TODO
echo -e "\e[3;4;38;5;46;48;5;95m求求各位给个star\e[0m"
echo -e "\033[32m自动化安装脚本:https://github.com/lux-QAQ/Manyana_deploy\033[0m"
echo "机器人实现：https://github.com/avilliai/Eridanus"
echo -e "\033[33m如果出现问题请查看文档 https://eridanus-doc.netlify.app/\033[0m"
echo -e "\033[33m如有疑问欢迎加群\033[0m ： \033[42m913122269\033[0m"
echo -e "\033[32m-------------------------------------------------------------------------------------------------\n\033[0m"
echo -e "\033[32m         \033[0m\033[1;41;32m 严禁商用声明 \033[0m\033[32m         \033[0m\n"
echo -e "\033[1;31m本项目遵守\033[0m \033[1;4;36mCreative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)\033[0m \033[1;31m协议。"
echo -e "未经许可，严禁将该项目用于任何商业用途。任何人将该项目商用所获取的任何非法利益与本项目无关。\033[0m"
echo -e "\033[3;4;31m如果你是付费后获取的本脚本，那恭喜你\033[0m\033[3;4;32m被骗了\033[0m\033[3;4;31m。\033[0m\n"
echo -e "\033[32m         \033[0m\033[1;41;32m 严禁商用声明 \033[0m\033[32m         \033[0m\n\n"
echo -e "\033[32m-------------------------------------------------------------------------------------------------\n\033[0m"
echo -e "\033[32m脚本执行完毕\n\033[0m"

